package com.chen.common.security.granter;

import com.chen.base.utils.SpringContextHolder;
import com.chen.common.security.token.MobileAuthenticationToken;
import com.chen.root.constant.CommonCons;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.OAuth2Request;
import org.springframework.security.oauth2.provider.TokenRequest;
import org.springframework.security.oauth2.provider.token.AbstractTokenGranter;

import java.util.LinkedHashMap;
import java.util.Map;

@Slf4j
public class MobileCodeTokenGranter extends AbstractTokenGranter {
    private static final String GRANT_TYPE = "sms_code";

    private final AuthenticationManager authenticationManager;

    public MobileCodeTokenGranter(AuthenticationManager authenticationManager, AuthorizationServerEndpointsConfigurer endpoints) {
        super(endpoints.getTokenServices(), endpoints.getClientDetailsService(), endpoints.getOAuth2RequestFactory(), GRANT_TYPE);
        this.authenticationManager = authenticationManager;
    }

    /**
     * 在此方法中验证code是否正确
     */
    @Override
    protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
        Map<String, String> parameters = new LinkedHashMap<>(tokenRequest.getRequestParameters());
        String mobile = parameters.get("mobile");
        String code = parameters.get("code");

        RedisTemplate redisTemplate = SpringContextHolder.getBean(RedisTemplate.class);
        String cacheCode = (String) redisTemplate.opsForValue().get(CommonCons.LOGIN_VERIFY_CODE + mobile);
        if (cacheCode == null){
            throw new OAuth2Exception("验证码不存在或已过期，请确认手机或验证码是否无误！");
        }
        if (!cacheCode.equals(code)){
            throw new OAuth2Exception("验证码错误!");
        }

        Authentication userAuth = new MobileAuthenticationToken(mobile, code);
        ((AbstractAuthenticationToken) userAuth).setDetails(parameters);
        userAuth = authenticationManager.authenticate(userAuth);
        if (userAuth == null || !userAuth.isAuthenticated()) {
            throw new InvalidGrantException("Could not authenticate mobile: " + mobile);
        }

        OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);
        return new OAuth2Authentication(storedOAuth2Request, userAuth);
    }
}